package com.esunrising.clickhouse.utils;

import com.clickhouse.jdbc.ClickHouseDataSource;

import java.sql.*;
import java.util.Properties;
import java.util.ResourceBundle;

public class ClickhouseUtil {
    private static final String DRIVERCLASS;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;

    static {
        DRIVERCLASS = ResourceBundle.getBundle("application").getString("clickhouse.driverClass");
        URL = ResourceBundle.getBundle("application").getString("clickhouse.url");
        USERNAME = ResourceBundle.getBundle("application").getString("clickhouse.username");
        PASSWORD = ResourceBundle.getBundle("application").getString("clickhouse.password");
    }

    static {
        try {
            Class.forName(DRIVERCLASS);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        Properties properties = new Properties();
        properties.setProperty("user", USERNAME);
        properties.setProperty("password", PASSWORD);
        ClickHouseDataSource dataSource = new ClickHouseDataSource(URL, properties);
        Connection con = dataSource.getConnection();
        //Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);

        return con;
    }

    public static void close(AutoCloseable... closes){
        for (AutoCloseable close : closes) {
            if(close!=null){
                try{
                    close.close();
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    close=null;
                }
            }
        }
    }

    // 关闭操作
    public static void closeConnection(Connection con) throws SQLException {
        if (con != null) {
            con.close();
        }
    }

    public static void closeStatement(Statement st) throws SQLException {
        if (st != null) {
            st.close();
        }
    }

    public static void closePreparedStatement(PreparedStatement st) throws SQLException {
        if (st != null) {
            st.close();
        }
    }

    public static void closeResultSet(ResultSet rs) throws SQLException {
        if (rs != null) {
            rs.close();
        }
    }
}
